package com.xncoding.Semaphore;

import java.util.concurrent.Semaphore;

public class SemaphoreTest {
    public static void main(String[] args) {
        Parking parking = new Parking(3);// 只能停3辆车的停车场

        for (int i = 0; i < 8; i++) {
            // 每一个线程表示一辆车到停车场停车
            new Thread() {
                public void run() {
                    parking.park();// 进入停车场
                };
            }.start();
        }
    }

    static class Parking {
        private Semaphore semaphore;// 信号量

        Parking(int count) {
            semaphore = new Semaphore(count);
        }

        public void park() {
            try {
                semaphore.acquire();// 获取许可
                long time = (long) (Math.random() * 10);
                System.out.println(Thread.currentThread().getName() + "进入停车场，停车" + time + "秒...");
                Thread.sleep(time);// 获取许可
                System.out.println(Thread.currentThread().getName() + "开出停车场...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
            }
        }
    }
}
